package com.dms.modules.message.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.dms.modules.message.entity.ChatMessage;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
import java.util.Map;

@Mapper
public interface ChatMessageMapper extends BaseMapper<ChatMessage> {
    
    /**
     * 将消息标记为已读
     */
    @Update("UPDATE chat_message SET status = 1 WHERE receiver_id = #{receiverId} AND sender_id = #{senderId} AND status = 0")
    int markAsRead(@Param("receiverId") Long receiverId, @Param("senderId") Long senderId);
    
    /**
     * 获取未读消息数
     */
    @Select("SELECT COUNT(*) FROM chat_message WHERE receiver_id = #{userId} AND status = 0")
    int getUnreadCount(@Param("userId") Long userId);

    /**
     * 获取指定用户发来的未读消息数
     */
    @Select("SELECT COUNT(*) FROM chat_message WHERE receiver_id = #{receiverId} AND sender_id = #{senderId} AND status = 0")
    int getUnreadCountFromUser(@Param("receiverId") Long receiverId, @Param("senderId") Long senderId);

    /**
     * 获取与用户有过聊天的所有用户ID列表（按最新消息时间排序）
     */
    @Select("SELECT other_user_id, MAX(last_time) as last_time FROM (" +
            "  SELECT sender_id as other_user_id, create_time as last_time FROM chat_message WHERE receiver_id = #{userId} " +
            "  UNION ALL " +
            "  SELECT receiver_id as other_user_id, create_time as last_time FROM chat_message WHERE sender_id = #{userId}" +
            ") t WHERE other_user_id != #{userId} GROUP BY other_user_id ORDER BY MAX(last_time) DESC")
    List<Map<String, Object>> getContactIds(@Param("userId") Long userId);

    /**
     * 获取与指定用户的最新一条消息
     */
    @Select("SELECT * FROM chat_message WHERE " +
            "((sender_id = #{userId} AND receiver_id = #{contactId}) OR " +
            "(sender_id = #{contactId} AND receiver_id = #{userId})) " +
            "ORDER BY create_time DESC LIMIT 1")
    ChatMessage getLastMessage(@Param("userId") Long userId, @Param("contactId") Long contactId);
} 